# coding: utf-8
from lifegame import LifeGame
import pygame
import time
import sys

def render(game, on_tick=None):
    pygame.init()
    lifes = (game.width, game.height)
    unitsize = (5, 5)
    size = (lifes[0]*(unitsize[0]+1)+1, lifes[1]*(unitsize[1]+1)+1)
    screen = pygame.display.set_mode(size)


    alive_suf = pygame.Surface(unitsize)
    alive_suf.fill(pygame.Color('green'))
    dead_suf = pygame.Surface(unitsize)
    dead_suf.fill(pygame.Color('gray'))

    grid = pygame.Surface(size)
    grid.fill(pygame.Color('white'))
    # draw the grid.
    for i in range(lifes[0]+1): # row lines
        pygame.draw.line(grid, pygame.Color('black'),
                (0, i*(unitsize[1]+1)),
                (size[0]-1, i*(unitsize[1]+1)))
    for i in range(lifes[1]+1): # col lines
        pygame.draw.line(grid, pygame.Color('black'),
                (i*(unitsize[0]+1), 0),
                (i*(unitsize[0]+1), size[1]-1))

    alive = pygame.Surface(unitsize)
    alive.fill(pygame.Color('green'))
    dead = pygame.Surface(unitsize)
    dead.fill(pygame.Color('gray'))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
        screen.fill(pygame.Color('white'))
        screen.blit(grid, (0,0))
        for y,row in enumerate(game.lifes):
            for x,life in enumerate(row):
                if life:
                    screen.blit(alive,(x*(unitsize[0]+1)+1,y*(unitsize[1]+1)+1))
                else:
                    screen.blit(dead,(x*(unitsize[0]+1)+1,y*(unitsize[1]+1)+1))
        if on_tick:
            on_tick()
        pygame.display.flip()

if __name__=='__main__':
    if len(sys.argv)==3:
        game = LifeGame(width=int(sys.argv[1]),height=int(sys.argv[2]))
    else:
        game = LifeGame(width=60,height=60)
    render(game, on_tick=game.round)
